from datetime import datetime, timedelta

from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404
from django.conf import settings
from django.http import HttpResponse, JsonResponse, Http404, FileResponse
from django.views.decorators.csrf import csrf_exempt
from django.db import transaction
from django.utils import timezone

from .models import (
    Questionnaire, Dimension, Question,
    UserQuestionnaire, UserDimensionScore, UserAnswer, UserQuestionnaireReport
)

import os
import json
import requests

# Create your views here.

all_url = "192.168.1.101"
# all_url = "172.20.0.89"

def save_report(all_score: int, score_all: list, dimensions, question, request, q_name, user_questionnaire):
    """
    保存问卷数据
    """
    url = f"http://{all_url}:8001/get_doc"
    # url = "http://127.0.0.1:8001/get_doc"
    data1 = {
        "data": {
            "all_score": all_score,
            "score_all": score_all,
            "dimensions": dimensions,
            "eval": question
        }
    }
    response = requests.post(url, json=data1)
    # 检查是否成功并保存返回的 Word 文件
    if response.status_code == 200:
        reports_dir = os.path.join(settings.BASE_DIR, 'media', 'reports')
        os.makedirs(reports_dir, exist_ok=True)
        with open(f"./media/reports/{q_name + '_' + request.user.username}.docx", "wb") as f:
            f.write(response.content)
            UserQuestionnaireReport.objects.update_or_create(
                user_questionnaire=user_questionnaire,  # 查找条件
                defaults={
                    'file': f"./media/reports/{q_name + '_' + request.user.username}.docx",
                    'generated_at': timezone.now()
                }
            )
        print(f"Word 文档已保存为 {request.user.username}.docx")
    else:
        print("请求失败：", response.status_code)

@login_required(login_url="/login")
def question_page(request):
    """
    问卷页面
    """
    if request.method == "POST":
        pass
    return render(request, 'psychological_assessment.html')


@login_required(login_url="/login")
def question_list(request):
    """
    获取问卷列表API
    """
    try:
        # 只获取启用的问卷
        questionnaires = Questionnaire.objects.filter(is_active=True).values(
            'id', 'name', 'question_id', 'description',
            'sub_description', 'person', 'duration', 'difficulty'
        )

        questionnaire_list = {
            'questionnaires': list(questionnaires)
        }

        return JsonResponse(questionnaire_list, safe=False)

    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
@login_required(login_url="/login")
def question_data(request):
    """
    获取问卷的具体数据API
    """
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            title = data.get("title", "")

            # 根据问卷名称获取问卷
            questionnaire = get_object_or_404(
                Questionnaire,
                question_id=title,
                is_active=True
            )

            # 构建问卷数据结构
            questionnaire_data = {
                'id': questionnaire.question_id,
                'title': questionnaire.name,
                'description': questionnaire.description,
                'sub_description': questionnaire.sub_description,
                'person': questionnaire.person,
                'duration': questionnaire.duration,
                'difficulty': questionnaire.difficulty,
                'dimensions': [],
                'questions': []
            }

            # 获取维度信息
            dimensions = questionnaire.dimensions.all().order_by('id')
            for dimension in dimensions:
                dimension_data = {
                    'id': dimension.id,
                    'name': dimension.name,
                    'description': dimension.description,
                    'weight': float(dimension.weight)
                }
                questionnaire_data['dimensions'].append(dimension_data)

            # 获取问题信息
            questions = questionnaire.questions.all().order_by('dimension', 'order')
            for question in questions:
                question_data = {
                    'id': question.id,
                    'title': question.title,
                    'type': question.question_type,
                    'dimension_id': question.dimension.id,
                    'dimension_name': question.dimension.name,
                    'options': question.options or [],
                    'is_required': question.is_required,
                    'order': question.order
                }
                questionnaire_data['questions'].append(question_data)
            print(questionnaire_data)
            return JsonResponse(questionnaire_data, safe=False)

        except Exception as e:
            # No Questionnaire matches the given query
            print("error", e)
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Method not allowed'}, status=405)


@csrf_exempt
@login_required(login_url="/login")
def question_submit(request):
    """
    提交问卷答案API
    """
    if request.method == "POST":
        # try:
        # 记录每道题的得分
        score_all = []
        data = json.loads(request.body)
        questionnaire_name = data.get("questionnaireName", "")
        answers = data.get("answers", {})

        # 获取问卷
        questionnaire = get_object_or_404(
            Questionnaire,
            name=questionnaire_name,
            is_active=True
        )

        with transaction.atomic():
            # 获取或创建用户问卷记录
            user_questionnaire, created = UserQuestionnaire.objects.get_or_create(
                user=request.user,
                questionnaire=questionnaire,
                defaults={
                    'status': 'in_progress',
                    'started_at': timezone.now()
                }
            )

            # 如果是新创建的记录，设置开始时间
            if created:
                user_questionnaire.started_at = timezone.now()
                user_questionnaire.status = 'in_progress'
                user_questionnaire.save()

            if not created:
                user_questionnaire.updated_at = timezone.now()
                user_questionnaire.status = 'in_progress'  # 可选：也可以更新状态
                user_questionnaire.save()

            # 计算分数和处理答案
            total_score = 0
            dimension_scores = {}

            # 获取所有问题
            questions = questionnaire.questions.all()

            # 先处理每个问题的答案和得分
            question_scores = {}  # 存储每个问题的得分，用于维度计算

            for question in questions:
                # 获取用户对这道题的答案
                answer_key = str(question.order) if str(question.order) in answers else str(question.id)
                user_answer_value = answers.get(answer_key)

                if user_answer_value is not None:
                    # 计算这道题的得分
                    question_score = calculate_question_score(question, user_answer_value)
                    score_all.append(question_score)
                    total_score += question_score

                    # 累计维度得分
                    dimension_id = question.dimension.id
                    if dimension_id not in dimension_scores:
                        dimension_scores[dimension_id] = {
                            'dimension': question.dimension,
                            'score': 0,
                            'question_count': 0
                        }
                    dimension_scores[dimension_id]['score'] += question_score
                    dimension_scores[dimension_id]['question_count'] += 1

                    # 保存或更新用户答案
                    UserAnswer.objects.update_or_create(
                        user_questionnaire=user_questionnaire,
                        question=question,
                        defaults={
                            'answer_options': user_answer_value if question.question_type != 'text' else None,
                            'answer_text': str(user_answer_value) if question.question_type == 'text' else '',
                            'score': question_score,
                            'answered_at': timezone.now()
                        }
                    )

            # 更新用户问卷总分
            user_questionnaire.total_score = total_score
            user_questionnaire.status = 'completed'
            user_questionnaire.completed_at = timezone.now()
            user_questionnaire.save()

            # 保存维度得分
            dimension_results = []
            for dimension_id, dim_data in dimension_scores.items():
                dimension = dim_data['dimension']
                score = dim_data['score']

                UserDimensionScore.objects.update_or_create(
                    user_questionnaire=user_questionnaire,
                    dimension=dimension,
                    defaults={
                        'score': score,
                        'percentage': 0  # 根据需要计算百分比
                    }
                )

                dimension_results.append({
                    'name': dimension.name,
                    'score': score
                })

            # 生成报告（您可以根据需要实现这个函数）
            dimensions = Dimension.objects.filter(questionnaire_id=questionnaire.id)
            evals = []
            for dimension_data in dimensions:
                evals.append({"name": dimension_data.name, "text": dimension_data.description, "help": dimension_data.help})
            print("evals", evals)
            print("total_score", total_score)
            print("score_all", score_all)
            print("dimensions", dimensions)
            save_report(total_score, score_all, dimension_results, evals, request, questionnaire.question_id, user_questionnaire)

            return JsonResponse({
                'success': True,
                'total_score': total_score,
                'dimension_scores': dimension_results,
                'message': '问卷提交成功'
            })

        # except Exception as e:
        #     print(e)
        #     return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Method not allowed'}, status=405)

@csrf_exempt
@login_required(login_url="/login")
def history_report(request):
    """
    获取历史报告API
    """
    # 获取分页参数
    page = int(request.GET.get("page", 1))
    page_size = int(request.GET.get("page_size", 10))
    time_range = int(request.GET.get("timeRange", 1000))
    start_time = timezone.now() - timedelta(days=time_range)

    # 获取该用户的问卷记录，按创建时间降序
    questionnaires = UserQuestionnaire.objects.filter(
        user=request.user,
        updated_at__gte=start_time  # 只取 start_time 之后的记录
    ).order_by('-created_at')

    # 使用分页器
    paginator = Paginator(questionnaires, page_size)
    current_page = paginator.get_page(page)

    datas = []
    # 预取相关对象，避免循环中重复查询数据库
    current_page.object_list = current_page.object_list.select_related('questionnaire')

    for uq in current_page.object_list:
        # 尝试获取报告
        try:
            report = UserQuestionnaireReport.objects.get(user_questionnaire=uq)
            datas.append({
                'questionnaire_id': uq.questionnaire_id,
                'questionnaire_title': uq.questionnaire.name,  # select_related 避免再次查询
                'download_url': report.file.url,
                'created_at': uq.updated_at,
                'status': 'completed'
            })
        except UserQuestionnaireReport.DoesNotExist:
            # 如果没有生成报告，可以跳过或返回空
            datas.append({
                'questionnaire_name': uq.questionnaire.name,
                'download_url': None,
            })
    # 返回分页信息
    response_data = {
        'page': page,
        'page_size': page_size,
        'total_pages': paginator.num_pages,
        'total_count': paginator.count,
        'results': datas,
    }

    return JsonResponse(response_data)

@csrf_exempt
@login_required(login_url="/login")
def history_download(request):
    """
    下载历史报告API
    """
    # 获取id
    history_id = request.GET.get("history_id", "")
    if history_id == "":
        question_id = request.GET.get("question_id", "")
        print("question_id:", question_id)
        # 从数据库中取出数据
        question = Questionnaire.objects.get(
            question_id=question_id
        )
        questionnaire = UserQuestionnaire.objects.get(
            id=question.id,
            user=request.user
        )
    else:
        # 从数据库中取出数据
        questionnaire = UserQuestionnaire.objects.get(
            id=history_id,
            user=request.user
        )
    report_id = questionnaire.id
    report = UserQuestionnaireReport.objects.get(
        user_questionnaire=report_id
    )
    file_path = report.file.path
    file_path = os.path.join(settings.BASE_DIR, file_path)
    print(file_path)
    if not file_path:
        raise Http404("报告文件不存在")
    response = FileResponse(open(file_path, 'rb'), as_attachment=True, filename="report.docx")
    return response




def calculate_question_score(question, user_answer):
    """
    计算单个问题的得分
    """
    if not question.options:
        return 0

    try:
        if question.question_type in ['single', 'likert', 'rating']:
            # 单选题或评分题
            if isinstance(user_answer, int) and 0 <= user_answer < len(question.options):
                return question.options[user_answer].get('score', 0)

        elif question.question_type == 'multiple':
            # 多选题
            total_score = 0
            if isinstance(user_answer, list):
                for answer_index in user_answer:
                    if isinstance(answer_index, int) and 0 <= answer_index < len(question.options):
                        total_score += question.options[answer_index].get('score', 0)
            return total_score

        elif question.question_type == 'text':
            # 文本题通常不计分，或根据特定规则计分
            return 0

    except (IndexError, KeyError, TypeError):
        pass

    return 0




